import React, { useState, useEffect } from 'react';
import {
  Card,
  Upload,
  Button,
  message,
  Typography,
  Input,
  Select,
  Row,
  Col,
  Form,
  Divider,
} from 'antd';
import {
  UploadOutlined,
  CopyOutlined,
  SendOutlined,
  SaveOutlined,
} from '@ant-design/icons';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism';
import aiService from '@/services/ai-test-agent';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;


const EditableCodeBlock = ({ code, language, onSave }: { code: string; language: string; onSave: (newCode: string) => void }) => {
  const [isEditing, setIsEditing] = useState(false);
  const [editValue, setEditValue] = useState(code);

  useEffect(() => {
    setEditValue(code);
  }, [code]);

  const handleEditClick = () => {
    setIsEditing(true);
  };

  const handleSave = () => {
    onSave(editValue);
    setIsEditing(false);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
      handleSave();
    }
  };

  if (isEditing) {
    return (
      <div style={{ position: 'relative' }}>
        <TextArea
          value={editValue}
          onChange={(e) => setEditValue(e.target.value)}
          onKeyDown={handleKeyDown}
          autoSize={{ minRows: 15, maxRows: 30 }}
          style={{
            fontFamily: 'monospace',
            fontSize: 14,
            backgroundColor: '#1E1E1E',
            color: '#f8f8f2',
            padding: '16px',
            borderRadius: 6,
            whiteSpace: 'pre',
            overflowX: 'auto',
          }}
        />
        <Button
          icon={<SaveOutlined />}
          type="primary"
          onClick={handleSave}
          style={{ position: 'absolute', top: 16, right: 16 }}
        >
          保存
        </Button>
      </div>
    );
  }

  return (
    <div onClick={handleEditClick} style={{ cursor: 'pointer' }}>
      <SyntaxHighlighter
        language={language}
        style={tomorrow}
        showLineNumbers
        wrapLines
        customStyle={{
          borderRadius: 6,
          fontSize: 14,
          backgroundColor: '#1E1E1E',
          whiteSpace: 'pre-wrap',
          fontFamily: 'monospace',
          padding: '16px',
          maxHeight: '80vh',
          overflowY: 'auto',
        }}
        lineProps={() => ({
          style: { whiteSpace: 'pre-wrap' },
        })}
      >
        {code}
      </SyntaxHighlighter>
    </div>
  );
};

const TestCase: React.FC = () => {
  const [fileContent, setFileContent] = useState('');
  const [fileName, setFileName] = useState('');
  const [inputText, setInputText] = useState('');
  const [engine, setEngine] = useState<'playwright' | 'selenium'>('playwright');
  const [loading, setLoading] = useState(false);

  const beforeUpload = (file: File) => {
    const isRobot = file.name.endsWith('.robot') || file.name.endsWith('.txt');
    if (!isRobot) {
      message.error('只能上传 .robot 或 .txt 文件');
    }
    return isRobot;
  };

  const handleFileRead = (file: File) => {
    setFileName(file.name);
    const reader = new FileReader();

    reader.onload = (e) => {
      const raw = e.target?.result as string;
      const cleaned = raw.replace(/\\n/g, '\n');
      let content = cleaned;
      if (/^".*\\n.*"$/.test(cleaned)) {
        try {
          content = JSON.parse(cleaned);
        } catch {
          // 忽略解析失败
        }
      }
      setFileContent(content);
    };

    reader.readAsText(file);
    return false;
  };

  const handleCopy = () => {
    if (!fileContent) {
      message.warning('暂无内容可复制');
      return;
    }
    navigator.clipboard.writeText(fileContent);
    message.success('已复制 .robot 内容到剪贴板');
  };

  const handleSaveContent = (newContent: string) => {
    setFileContent(newContent);
    message.success('内容已更新');
  };

  const handleAiGenerate = async () => {
    if (!inputText.trim()) {
      message.warning('请输入用例描述');
      return;
    }

    setLoading(true);
    try {
      const response = await aiService.robot.generateScript({
          engine: engine,
          user_input: inputText,
      });

      if (!response) throw new Error('生成失败');
      const data = await response.script;
      setFileContent(data);
      message.success('用例生成成功');
    } catch (error) {
      console.error(error);
      message.error('用例生成失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <Card
        bordered={false}
        style={{ borderRadius: 8 }}
        title={
          <Title level={4} style={{ marginBottom: 0 }}>
            Robot Framework 格式化展示与 AI 用例生成器
          </Title>
        }
      >
        <Row gutter={24}>
          {/* 左侧 - AI生成用例部分 */}
          <Col xs={24} md={8}>
            <Card
              title="AI 生成测试用例"
              bordered
              style={{
                backgroundColor: '#f9f9f9',
                borderRadius: 6,
                boxShadow: '0 1px 4px rgba(0, 0, 0, 0.05)',
              }}
              extra={<Text type="secondary">输入自然语言需求</Text>}
            >
              <Form layout="vertical">
                <Form.Item label="选择引擎" labelAlign="left">
                  <Select
                    value={engine}
                    onChange={(value) => setEngine(value)}
                    style={{ width: '100%', borderRadius: 6 }}
                    size="middle"
                  >
                    <Option value="playwright">Playwright</Option>
                    <Option value="selenium">Selenium</Option>
                  </Select>
                </Form.Item>

                <Form.Item label="测试用例需求" labelAlign="left">
                  <TextArea
                    rows={6}
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    placeholder="例如：测试用户成功登录流程，使用Playwright进行端到端测试"
                    style={{ borderRadius: 6, fontSize: 14 }}
                  />
                </Form.Item>

                <Button
                  icon={<SendOutlined />}
                  type="primary"
                  onClick={handleAiGenerate}
                  loading={loading}
                  block
                  style={{ marginTop: 16 }}
                >
                  AI 生成用例
                </Button>
              </Form>

              <Divider />

              <Upload
                beforeUpload={beforeUpload}
                showUploadList={false}
                accept=".robot,.txt"
                customRequest={({ file }) => handleFileRead(file as File)}
              >
                <Button icon={<UploadOutlined />} block>
                  上传 .robot 文件
                </Button>
              </Upload>

              {fileName && (
                <Text strong style={{ marginTop: 8, display: 'block' }}>
                  当前文件：{fileName}
                </Text>
              )}
            </Card>
          </Col>

          {/* 右侧 - 可编辑的代码块 */}
          <Col xs={24} md={16}>
            <Card
              title="Robot Framework 内容预览"
              bordered
              style={{
                borderRadius: 6,
                height: '100%',
              }}
              extra={
                fileContent && (
                  <div style={{ display: 'flex', gap: 8 }}>
                    <Button
                      icon={<CopyOutlined />}
                      onClick={handleCopy}
                      style={{ padding: 0, minWidth: 120 }}
                    >
                      复制内容
                    </Button>
                  </div>
                )
              }
            >
              {fileContent ? (
                <EditableCodeBlock
                  code={fileContent}
                  language="robot"
                  onSave={handleSaveContent}
                />
              ) : (
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    height: '100%',
                    backgroundColor: '#fafafa',
                  }}
                >
                  <Text type="secondary">暂无内容，可上传文件或使用 AI 生成</Text>
                </div>
              )}
            </Card>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default TestCase;
